package com.app.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.net.UnknownHostException;

/**
 * @author 王鑫
 * @create 2020 -11 -23 14:33
 * 序列化json数据到Redis中
 */
@Configuration
public class RedisAutoConfiguration {
    //序列化为json到缓存中
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration() {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration = redisCacheConfiguration
                .serializeKeysWith(
                        RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.string()))
                .serializeValuesWith(
                        RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json()));
        return redisCacheConfiguration;
    }


    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        //下面都是自定义序列化器。默认都是序列化为JSON,下面是自己修改序列化类型
        //redis的key都使用String序列化
        template.setKeySerializer(RedisSerializer.string());
        //redis的value都使用Json序列化
        template.setValueSerializer(RedisSerializer.json());
        //Hash的field都使用String序列化
        template.setHashKeySerializer(RedisSerializer.string());
        //Hash的value都使用Json序列化
        template.setHashValueSerializer(RedisSerializer.json());
        return template;
    }
}
